package cn.scy.handler;

import cn.hutool.core.date.DateUtil;
import cn.scy.util.UserUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * Mybatis Plus 插入或者更新时指定字段设置值
 *
 * @author scy
 */
@Component
public class MybatisPlusFillHandler implements MetaObjectHandler {

    private static final String CREATE_BY = "createBy";

    private static final String CREATE_TIME = "createTime";

    private static final String UPDATE_BY = "updateBy";

    private static final String UPDATE_TIME = "updateTime";

    @Override
    public void insertFill(MetaObject metaObject) {
        if (metaObject.hasSetter(CREATE_BY)) {
            this.strictInsertFill(metaObject, CREATE_BY, String.class, UserUtil.getCurrentUserId());
        }
        if (metaObject.hasSetter(CREATE_TIME)) {
            this.strictInsertFill(metaObject, CREATE_TIME, Date.class, DateUtil.date());
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        if (metaObject.hasSetter(UPDATE_BY)) {
            this.fillStrategy(metaObject, UPDATE_BY, UserUtil.getCurrentUserId());
        }
        if (metaObject.hasSetter(UPDATE_TIME)) {
            this.fillStrategy(metaObject, UPDATE_TIME, DateUtil.date());
        }
    }

}
